package com.yunyv.iotudpserve.TCP.listenerNew;

import cn.dev33.satoken.annotation.SaIgnore;
import com.yunyv.iotudpserve.common.Request;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/********************************************************************************
 ** author： zhangtianhe
 ** date：2024年06月17日 14:40
 ** description&desc：
 *********************************************************************************/
@Slf4j
@RestController
@SaIgnore
@RequestMapping("/tcp")
@Api(tags = "发送TCp数据")
public class TCPClient {
    @SaIgnore
    @PostMapping("/send")
    public void send(@RequestBody @Validated Request<String> request) {
        String serverIp = "127.0.0.1"; // 服务器IP地址
        int serverPort = 62011;        // 服务器端口号
//        String message = request.getData(); // 要发送的消息
        String message ="ZABC1208084855P{\"sensorDatas\":[{\"flag\":1,\"gas_value\":0,\"gas_dec\":0,\"gas_status\":1,\"gas_type\":50,\"gas_unit\":1,\"alarml\":20,\"alarmh\":50,\"gas_range\":100},{\"flag\":2,\"gas_value\":209,\"gas_dec\":1,\"gas_status\":1,\"gas_type\":5,\"gas_unit\":2,\"alarml\":195,\"alarmh\":235,\"gas_range\":300},{\"flag\":3,\"gas_value\":0,\"gas_dec\":0,\"gas_status\":1,\"gas_type\":4,\"gas_unit\":3,\"alarml\":50,\"alarmh\":150,\"gas_range\":1000},{\"flag\":4,\"gas_value\":0,\"gas_dec\":0,\"gas_status\":1,\"gas_type\":3,\"gas_unit\":3,\"alarml\":20,\"alarmh\":50,\"gas_range\":100}]}";
        try (Socket socket = new Socket(serverIp, serverPort);
             OutputStream outputStream = socket.getOutputStream()) {
            // 将消息转换为字节数组
            byte[] bytesToSend = message.getBytes();

            // 发送消息
            outputStream.write(bytesToSend);
// 关闭Socket
            socket.close();
            System.out.println("TCP message==========="+message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
